<!--
 * @Description: FormItem
 * @Author: zyj
 * @Date: 2022-06-11 14:55:28
 * @LastEditors: zyj
 * @LastEditTime: 2022-06-11 16:47:13
-->
<template>
  <div class="k-form-item">
    <p class="label">{{ label }}</p>
    <div>
      <slot></slot>
      <p v-if="errorStatus" class="error-message">{{ errorMessage }}</p>
    </div>
  </div>
</template>

<script>
import schema from 'async-validator'
export default {
  name: 'KFormItem',
  data() {
    return {
      errorStatus: false,
      errorMessage: ''
    }
  },
  inject: ['form'], // 注入form，获取model和rules
  props: ['label', 'prop'],
  created() {
    this.$on('validate', this.validate)
  },
  mounted() {
    // 挂载到form上时，派发一个添加事件
    if (this.prop) {
      this.$parent.$emit('FormItemAdd', this)
    }
  },
  methods: {
    validate() {
      return new Promise((resolve) => {
        // 校验当前项：依赖async-validate
        const descriptor = {
          //校验规则
          [this.prop]: this.form.rules[this.prop]
        }
        const validator = new schema(descriptor)
        // 使用es6计算属性动态设置key
        console.log(this.form.model)
        validator.validate({ [this.prop]: this.form.model[this.prop] }, (errors) => {
          if (errors) {
            // 校验失败
            this.errorStatus = true
            this.errorMessage = errors[0].message
            resolve(false) //校验失败
          } else {
            this.errorStatus = false
            this.errorMessage = ''
            resolve(true)
          }
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
.k-form-item {
  display: flex;
  .label {
    padding: 0 10px;
    height: 48px;
  }
  .error-message {
    color: red;
    font-size: 12px;
  }
}
</style>